import React from 'react';
import {connect} from 'react-redux';
import {
    StyleSheet,
    Text,
    TextInput,
    View,
    ScrollView,
    Image,
    InteractionManager,
    TouchableHighlight,
    TouchableOpacity,
    Modal,
    Alert,
} from 'react-native';

import CLNavigatorHeader from '../../component/CLNavigatorHeader'

import styles from './styles'

import {getUserDetail, changeUser, editUser} from './actions';

import {chooseImage, toast} from '../../utils/NativeUtil'
import config from '../../config/config';
import {naviBack} from '../../navigatorApp/actions'

import {getQiniuToken} from '../../utils/commonHttp'

import ActionSheet from 'react-native-actionsheet'

import DatePicker from 'react-native-datepicker'

const CANCEL_INDEX = 0
const options = ['取消', '男', '女'];

const imageOptions = ['取消', '拍照上传', '选择图片']

class UserEdit extends React.Component {

    static navigationOptions = ({navigation, screenProps}) => {
        const {params = {}} = navigation.state;
        let header = (<CLNavigatorHeader navigation={navigation} title="账号编辑" rightTitle="保存"
                                         rightAction={params.submit}/>);
        return {header}
    };

    constructor(props) {
        super(props);
        this.state = {date: ""}
    }

    componentDidMount() {
        this.props.navigation.setParams({submit: this.submit});
        const {dispatch} = this.props;
        const token = this.props.token;
        InteractionManager.runAfterInteractions(() => {
            this.props.getUserDetail(token);
        });
    }

    editUser = () => {
        this.ImageActionSheet.show()
    }

    handleImagePress = (i) => {
        let type = "choose";
        let size_w = 400;
        let size_h = 400;
        if (i == 1) {
            type = "takephoto"
        } else if (i == 2) {
            type = "choose"
        } else {
            return;
        }

        const self = this;
        getQiniuToken((data) => {
            let params = {
                type: type,
                size_w: size_w,
                size_h: size_h,
                token: data.token,
                filetag: "shopuser"
            }
            chooseImage(params, (data) => {
                self.changeUserObject({portrait: config.qiniuUrl + data.imgs});
            });
        })
    }

    handlePress = (i) => {
        if (i == 1) {
            this.changeUserObject({sex: 1});
        } else if (i == 2) {
            this.changeUserObject({sex: 0});
        }
    }

    chooseSex = () => {
        this.ActionSheet.show()
    }

    onChangeText = (text) => {
        this.changeUserObject({username: text});
    }

    changeUserObject = (user) => {
        const newuser = Object.assign({}, this.props.user, user);
        this.props.changeUser(newuser)
    }

    submit = () => {
        const user = this.props.user;

        if (user.portrait == undefined || user.portrait == "") {
            toast("请上传头像");
            return;
        }
        let p = /^[\u4E00-\u9FA5A-Za-z0-9_]{1}[\u4E00-\u9FA5A-Za-z0-9_\s]*[\u4E00-\u9FA5A-Za-z0-9_]{1}$/
        if (user.username == undefined || !p.test(user.username)) {
            toast("请按照正确的格式输入用户名");
            return;
        }
        if (user.username.length >= 20) {
            toast("昵称太长,请控制在20以内");
            return;
        }
        this.props.editUser(this.props.token, user, () => {
            toast("保存成功");
            this.props.naviBack();
        });
    }

    render = () => {
        const portrait = {
            uri: this.props.user.portrait,
            width: 80,
            height: 80
        };

        let headView = <Image style={styles.my_head_img} source={portrait}/>

        if (this.props.user.portrait == undefined || this.props.user.portrait == ""){
            headView = <Image
                style={{
                    width: 80,
                    height: 80
                }}
            source={require('../../image/takephoto.png')}/>
        }

        let sexValue = "";

        if (this.props.user.sex == 1) {
            sexValue = "男"
        } else if (this.props.user.sex == 0) {
            sexValue = "女"
        }

        return <View style={{flex: 1}}>
            <ScrollView>
                <TouchableHighlight
                underlayColor='#eee'
                onPress={() => {
                    this.editUser()
                }}>
                    <View style={styles.headRow}>
                        {headView}
                    </View>
                </TouchableHighlight>
                <View style={{height: 1, backgroundColor: '#eee'}}/>
                <View style={styles.row}>
                    <TextInput
                        value={this.props.user.username}
                        placeholder="请输入昵称(数字、字母、汉字、下划线)"
                        editable={true}
                        underlineColorAndroid={'transparent'}
                        returnKeyType="done"
                        style={{padding: 0, flex: 1, borderWidth: 0,}}
                        onChangeText={(text) => this.changeUserObject({username: text})}
                    />
                </View>
                {/* <View style={{height: 1, backgroundColor: '#eee'}}/> */}
                {/* <View style={styles.row}>
                    <Text>手机号码</Text>
                    <Text>{this.props.user.mobile}</Text>
                </View> */}
                <View style={{height: 1, backgroundColor: '#eee'}}/>
                <TouchableHighlight style={{flex: 1}} onPress={() => {
                    this.chooseSex()
                }}>
                    <View style={styles.row}>
                        <Text>性别</Text>
                        <View style={styles.rowRight}>
                            <Text>{sexValue}</Text>
                            <Image style={{width: 20, height: 15}} source={require('../../image/img_right_grey.png')}/>
                        </View>
                    </View>
                </TouchableHighlight>
                <View style={{height: 1, backgroundColor: '#eee'}}/>
                <View style={styles.row}>
                    <Text >生日</Text>
                    <View style={styles.rowRight}>
                        <DatePicker
                            style={{backgroundColor: "white", width: 75}}
                            date={this.props.user.birthday}
                            mode="date"
                            showIcon={false}
                            placeholder="选择日期"
                            format="YYYY-MM-DD"
                            confirmBtnText="确定"
                            cancelBtnText="取消"
                            customStyles={{
                                dateInput: {
                                    borderWidth: 0,
                                }
                            }}
                            onDateChange={(date) => {
                                this.changeUserObject({birthday: date})
                            }}
                        />
                        <Image style={{width: 20, height: 15}} source={require('../../image/img_right_grey.png')}/>
                    </View>
                </View>
                <ActionSheet
                    ref={o => this.ActionSheet = o}
                    title="选择性别"
                    cancelButtonIndex={CANCEL_INDEX}
                    options={options}
                    onPress={this.handlePress}
                />
                <ActionSheet
                    ref={o => this.ImageActionSheet = o}
                    title="选择图片"
                    options={imageOptions}
                    cancelButtonIndex={CANCEL_INDEX}
                    onPress={this.handleImagePress}/>
            </ScrollView>
        </View>
    }
}

const mapStateToProps = state => ({
    token: state.mainmodel.userToken,
    user: state.user.user,
});

const mapDispatchToProps = dispatch => ({
    getUserDetail: (token) => {
        dispatch(getUserDetail(token))
    },
    changeUser: (user) => {
        dispatch(changeUser(user))
    },
    editUser: (token, user, callback) => {
        dispatch(editUser(token, user, callback));
    },
    naviBack : (routeName) => {
        dispatch(naviBack(routeName));
    }
}); 

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(UserEdit);
